<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>航班查询与路径规划系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 10px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #1a73e8;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: center;
            flex-wrap: nowrap;
        }
        .form-col {
            flex: 1;
            min-width: 0;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        select {
            width: 100%;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            background-color: white;
        }
        .radio-group, .weekday-checkboxes {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        .radio-group label, .weekday-checkboxes label {
            display: flex;
            align-items: center;
            font-weight: normal;
            cursor: pointer;
        }
        .radio-group input[type="radio"], .weekday-checkboxes input[type="checkbox"] {
            margin-right: 8px;
        }
        .weekday-checkboxes {
            gap: 15px;
        }
        button {
            background-color: #1a73e8;
            color: white;
            border: none;
            padding: 6px 15px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #1557b0;
        }
        .results {
            margin-top: 30px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .result-section {
            margin-bottom: 30px;
            padding: 10px;
            background-color: #fafafa;
            border-radius: 6px;
        }
        .result-section h3 {
            color: #1a73e8;
            margin-top: 0;
        }
        .flight-card {
            background-color: white;
            padding: 5px;
            margin-bottom: 8px;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .flight-info {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .flight-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .airline-info {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #666;
        }
        .airline-code {
            background-color: #1a73e8;
            color: white;
            padding: 1px 3px;
            border-radius: 3px;
            font-weight: bold;
        }
        .airline-name {
            font-size: 13px;
        }
        .flight-basic {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: nowrap;
            gap: 15px;
        }
        .flight-details {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            font-size: 14px;
            color: #666;
        }
        .product {
            background-color: #f0f0f0;
            padding: 1px 4px;
            border-radius: 3px;
        }
        .flight-number {
            font-weight: bold;
            color: #1a73e8;
        }
        .route {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .city {
            font-weight: 500;
        }
        .arrow {
            color: #666;
        }
        .time-info {
            color: #666;
        }
        .schedule {
            font-size: 14px;
            color: #666;
            background-color: #f0f0f0;
            padding: 1px 4px;
            border-radius: 3px;
        }
        .transfer-route {
            padding: 7.5px;
            background-color: white;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .transfer-title {
            font-weight: bold;
            color: #1a5276;
            background-color: #d4e6f1;
            padding: 4px 6px;
            border-radius: 6px;
            margin-bottom: 10px;
            font-size: 16px;
        }
        .transfer-point {
            text-align: center;
            padding: 5px;
            background-color: #e8f0fe;
            color: #1a73e8;
            font-weight: bold;
            margin: 10px 0;
            border-radius: 4px;
        }
        .no-results {
            text-align: center;
            color: #666;
            padding: 20px;
            background-color: #fafafa;
            border-radius: 6px;
        }
        .suggestions {
            position: absolute;
            background-color: white;
            border: 1px solid #ddd;
            border-top: none;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            width: 100%;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: none;
        }
        .suggestion-item {
            padding: 5px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }
        .suggestion-item:hover {
            background-color: #f0f0f0;
        }
        .suggestion-item:last-child {
            border-bottom: none;
        }
        .form-col {
            position: relative;
        }
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
            }
            .flight-info {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>航班查询与路径规划系统</h1>
        
        <form id="flightSearchForm">
            <div class="form-group">
                <label>产品版本：</label>
                <div class="radio-group">
                    <label><input type="radio" name="version" value="666_winter" checked> 666冬季版</label>
                    <label><input type="radio" name="version" value="666_summer"> 666夏季版</label>
                    <label><input type="radio" name="version" value="2666_winter"> 2666冬季版</label>
                    <label><input type="radio" name="version" value="2666_summer"> 2666夏季版</label>
                   
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-col">
                    <label for="departure">出发地：</label>
                    <input type="text" id="departure" name="departure" placeholder="请输入出发地城市名称">
                    <div id="departureSuggestions" class="suggestions"></div>
                </div>
                
                <div class="form-col">
                    <label for="destination">目的地：</label>
                    <input type="text" id="destination" name="destination" placeholder="请输入目的地城市名称">
                    <div id="destinationSuggestions" class="suggestions"></div>
                </div>
            </div>
            
            <div class="form-group">
                <label>星期筛选（多选，默认全选）：</label>
                <div class="weekday-checkboxes">
                    <label><input type="checkbox" name="weekday" value="1" checked> 周一</label>
                    <label><input type="checkbox" name="weekday" value="2" checked> 周二</label>
                    <label><input type="checkbox" name="weekday" value="3" checked> 周三</label>
                    <label><input type="checkbox" name="weekday" value="4" checked> 周四</label>
                    <label><input type="checkbox" name="weekday" value="5" checked> 周五</label>
                    <label><input type="checkbox" name="weekday" value="6" checked> 周六</label>
                    <label><input type="checkbox" name="weekday" value="7" checked> 周日</label>
                </div>
            </div>
            
            <div class="form-row">
                <button type="submit">查询</button>
            </div>
        </form>
        
        <div class="results" id="resultsContainer">
            <!-- 查询结果将在这里显示 -->
        </div>
    </div>
    
    <script>
        // 全局变量存储城市列表
        let allCities = [];
        
        // 加载城市数据
        function loadCities() {
            const version = document.querySelector('input[name="version"]:checked').value;
            const xhr = new XMLHttpRequest();
            xhr.open('GET', `api.php?action=getCities&version=${version}`, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    allCities = JSON.parse(xhr.responseText);
                    console.log('加载城市数据成功:', allCities);
                }
            };
            xhr.send();
        }
        
        // 显示自动完成建议
        function showSuggestions(inputElement, suggestionsElement, cities) {
            suggestionsElement.innerHTML = '';
            
            if (cities.length === 0) {
                suggestionsElement.style.display = 'none';
                return;
            }
            
            cities.forEach(city => {
                const item = document.createElement('div');
                item.className = 'suggestion-item';
                item.textContent = city;
                item.addEventListener('click', function() {
                    inputElement.value = city;
                    suggestionsElement.style.display = 'none';
                });
                suggestionsElement.appendChild(item);
            });
            
            suggestionsElement.style.display = 'block';
        }
        
        // 过滤城市列表
        function filterCities(query) {
            if (!query) return [];
            return allCities.filter(city => 
                city.toLowerCase().includes(query.toLowerCase())
            );
        }
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            loadCities();
            
            const departureInput = document.getElementById('departure');
            const destinationInput = document.getElementById('destination');
            const departureSuggestions = document.getElementById('departureSuggestions');
            const destinationSuggestions = document.getElementById('destinationSuggestions');
            
            // 出发地输入框事件
            departureInput.addEventListener('input', function() {
                const query = this.value;
                const filteredCities = filterCities(query);
                showSuggestions(departureInput, departureSuggestions, filteredCities);
            });
            
            // 目的地输入框事件
            destinationInput.addEventListener('input', function() {
                const query = this.value;
                const filteredCities = filterCities(query);
                showSuggestions(destinationInput, destinationSuggestions, filteredCities);
            });
            
            // 点击页面其他地方隐藏建议框
            document.addEventListener('click', function(e) {
                if (!departureInput.contains(e.target) && !departureSuggestions.contains(e.target)) {
                    departureSuggestions.style.display = 'none';
                }
                if (!destinationInput.contains(e.target) && !destinationSuggestions.contains(e.target)) {
                    destinationSuggestions.style.display = 'none';
                }
            });
            
            // 表单提交事件
            document.getElementById('flightSearchForm').addEventListener('submit', function(e) {
                e.preventDefault();
                searchFlights();
            });
            
            // 版本切换事件
            document.querySelectorAll('input[name="version"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    loadCities();
                });
            });
        });
        
        // 获取选中的星期
        function getSelectedWeekdays() {
            const checkboxes = document.querySelectorAll('input[name="weekday"]:checked');
            const weekdays = Array.from(checkboxes).map(cb => cb.value);
            return weekdays.length > 0 ? weekdays : ['1','2','3','4','5','6','7'];
        }
        
        // 搜索航班
        function searchFlights() {
            const version = document.querySelector('input[name="version"]:checked').value;
            const departure = document.getElementById('departure').value;
            const destination = document.getElementById('destination').value;
            const weekdays = getSelectedWeekdays();
            const resultsContainer = document.getElementById('resultsContainer');
            
            // 显示加载状态
            resultsContainer.innerHTML = '<div class="loading">正在查询，请稍候...</div>';
            
            const xhr = new XMLHttpRequest();
            xhr.open('GET', `api.php?action=searchFlights&version=${version}&departure=${encodeURIComponent(departure)}&destination=${encodeURIComponent(destination)}&weekdays=${weekdays.join(',')}`, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    displayResults(response);
                }
            };
            xhr.send();
        }
        
        // 显示查询结果
        function displayResults(data) {
            const resultsContainer = document.getElementById('resultsContainer');
            resultsContainer.innerHTML = '';
            
            // 显示直达航班
            if (data.directFlights && data.directFlights.length > 0) {
                const directSection = document.createElement('div');
                directSection.className = 'result-section';
                directSection.innerHTML = `<h3>直达航班 (${data.directFlights.length})</h3>`;
                
                data.directFlights.forEach(flight => {
                    const flightCard = document.createElement('div');
                    flightCard.className = 'flight-card';
                    flightCard.innerHTML = createFlightCardHTML(flight);
                    directSection.appendChild(flightCard);
                });
                
                resultsContainer.appendChild(directSection);
            }
            
            // 显示中转航班
            if (data.transferRoutes && data.transferRoutes.length > 0) {
                const transferSection = document.createElement('div');
                transferSection.className = 'result-section';
                transferSection.innerHTML = `<h3>中转航班 (${data.transferRoutes.length})</h3>`;
                
                data.transferRoutes.forEach((route, index) => {
                    const transferRoute = document.createElement('div');
                    transferRoute.className = 'transfer-route';
                    
                    // 创建中转方案标题
                    const transferCount = route.length - 1; // 中转次数
                    let cityPath = '';
                    if (route.length > 0) {
                        // 构建城市路径：出发城市-中转城市1-中转城市2-...-目的地城市
                        cityPath = route[0].departure_city;
                        route.forEach(flight => {
                            cityPath += '-' + flight.arrival_city;
                        });
                    }
                    
                    const titleHtml = `<div class="transfer-title">中转方案${index + 1}：${cityPath}（中转${transferCount}次）</div>`;
                    
                    // 构建中转路径HTML
                    let routeHtml = '';
                    for (let i = 0; i < route.length; i++) {
                        const flight = route[i];
                        routeHtml += createFlightCardHTML(flight);
                        
                        // 添加中转点标识
                        if (i < route.length - 1) {
                            routeHtml += `<div class="transfer-point">在 ${flight.arrival_city} 中转</div>`;
                        }
                    }
                    
                    transferRoute.innerHTML = titleHtml + routeHtml;
                    transferSection.appendChild(transferRoute);
                });
                
                resultsContainer.appendChild(transferSection);
            }
            
            // 显示出发地航班列表
            if (data.flightsFromCity && data.flightsFromCity.length > 0) {
                const flightsSection = document.createElement('div');
                flightsSection.className = 'result-section';
                flightsSection.innerHTML = `<h3>从 ${document.getElementById('departure').value} 出发的航班 (${data.flightsFromCity.length})</h3>`;
                
                data.flightsFromCity.forEach(flight => {
                    const flightCard = document.createElement('div');
                    flightCard.className = 'flight-card';
                    flightCard.innerHTML = createFlightCardHTML(flight);
                    flightsSection.appendChild(flightCard);
                });
                
                resultsContainer.appendChild(flightsSection);
            }
            
            // 显示目的地航班列表
            if (data.flightsToCity && data.flightsToCity.length > 0) {
                const flightsSection = document.createElement('div');
                flightsSection.className = 'result-section';
                flightsSection.innerHTML = `<h3>到达 ${document.getElementById('destination').value} 的航班 (${data.flightsToCity.length})</h3>`;
                
                data.flightsToCity.forEach(flight => {
                    const flightCard = document.createElement('div');
                    flightCard.className = 'flight-card';
                    flightCard.innerHTML = createFlightCardHTML(flight);
                    flightsSection.appendChild(flightCard);
                });
                
                resultsContainer.appendChild(flightsSection);
            }
            
            // 如果没有任何结果
            if (!data.directFlights || data.directFlights.length === 0) {
                if (!data.transferRoutes || data.transferRoutes.length === 0) {
                    if (!data.flightsFromCity || data.flightsFromCity.length === 0) {
                        if (!data.flightsToCity || data.flightsToCity.length === 0) {
                            resultsContainer.innerHTML = '<div class="no-results">暂无符合条件的航班信息</div>';
                        }
                    }
                }
            }
        }
        
        // 判断是否为早班机（9点以前）
        function isEarlyFlight(departureTime) {
            const time = departureTime.split(':')[0];
            return parseInt(time) < 9;
        }
        
        // 获取航班时间分类
        function getFlightTimeCategory(departureTime) {
            return isEarlyFlight(departureTime) ? '早班机' : '晚班机';
        }
        
        // 获取航班时间分类颜色
        function getFlightTimeColor(departureTime) {
            return isEarlyFlight(departureTime) ? '#28a745' : '#dc3545'; // 绿色代表早班机，红色代表晚班机
        }
        
        // 创建航班卡片HTML
        function createFlightCardHTML(flight) {
            const airlineInfo = flight.airline ? `
                <div class="airline-info">
                    <span class="airline-code">${flight.airline.iata}</span>
                    <span class="airline-name">${flight.airline.name}</span>
                </div>
            ` : '';
            
            const timeCategory = getFlightTimeCategory(flight.departure_time);
            const timeColor = getFlightTimeColor(flight.departure_time);
            
            return `
                <div class="flight-info">
                    <div class="flight-header">
                        <span class="flight-number">${flight.flight_number}</span>
                        ${airlineInfo}
                    </div>
                    <div class="flight-basic">
                        <div class="route">
                            <span class="city">${flight.departure_city}</span>
                            <span class="arrow">→</span>
                            <span class="city">${flight.arrival_city}</span>
                        </div>
                        <span class="time-info" style="color: ${timeColor}; font-weight: bold;">
                            ${flight.departure_time} (${timeCategory})
                        </span>
                    </div>
                    <div class="flight-details">
                        <span class="schedule">${formatSchedule(flight.schedule)}</span>
                        <span class="product">适用产品：${flight.applicable_products.join(', ')}</span>
                    </div>
                </div>
            `;
        }
        
        // 格式化航班班期显示
        function formatSchedule(schedule) {
            const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
            let result = '班期：';
            for (let day of schedule) {
                result += `${weekdays[parseInt(day) - 1]} `;
            }
            return result.trim();
        }
    </script>
</body>
</html>